<template>
  <!-- 合同添加 -->
  <div class="contractInfo box">
    <el-divider content-position="left">{{
      $route.query.mode == "add" ? "添加合同" : "编辑合同"
    }}</el-divider>
    <!-- <div class="formBox"> -->
    <el-form
      :model="contractForm"
      :rules="rules"
      ref="addForm"
      label-width="auto"
      label-position="right"
      style="width: 100%"
    >
      <!-- <el-form-item label="合同编号" prop="num" required style="width: 100%">
          <p>{{ contractForm.num }}</p>
        </el-form-item> -->
      <el-card
        shadow="hover"
        header="基本信息"
        class="item-background"
        style="width: 100%"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联报价" prop="quotesData" class="formRow">
              <sc-table-select
                v-model="contractForm.quotesData"
                :apiObj="apiObj"
                style="width: 100%"
                :table-width="700"
                clearable
                collapse-tags
                collapse-tags-tooltip
                :props="quotesProps"
                @change="quotesChange"
                :disabled="$route.query.quoteId"
              >
                <template #header="{ form, submit }">
                  <el-form :inline="true" :model="form">
                    <el-form-item>
                      <el-input
                        v-model="form.search"
                        placeholder="报价名称"
                        clearable
                      ></el-input>
                    </el-form-item>
                    <el-button type="primary" @click="submit">查询</el-button>
                  </el-form>
                  <!-- <el-alert title="自定义FORM插糟 传递了form对象和提交方法" type="info" /> -->
                </template>
                <el-table-column
                  label="报价名称"
                  prop="quotesName"
                  min-width="150"
                ></el-table-column>
                <el-table-column
                  label="客户名称"
                  prop="customerName"
                  min-width="150"
                ></el-table-column>
                <el-table-column
                  label="报价总额"
                  prop="price"
                  width="100"
                ></el-table-column>
                <el-table-column
                  label="报价日期"
                  prop="createTime"
                  width="200"
                ></el-table-column>
              </sc-table-select>
              <el-button type="primary" @click="toQuoteDetail">详情</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="name" style="100%">
              <el-input
                v-model="contractForm.name"
                placeholder="请输入合同名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同简称">
              <el-input
                v-model="contractForm.simpleName"
                placeholder="请输入合同简称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方" prop="lessor">
              <el-input
                v-model="contractForm.lessor"
                placeholder="请输入甲方名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="甲方电话" prop="">
              <el-input
                v-model="contractForm.lessorPhone"
                placeholder="请输入甲方电话"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方" prop="partyBName">
              <el-input
                v-model="contractForm.partyBName"
                placeholder="请输入乙方名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="type">
              <el-select
                v-model="contractForm.type"
                placeholder="请选择合同类型"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in contractType"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同总额" prop="money">
              <el-input
                v-model="contractForm.money"
                placeholder="请输入合同金额"
                clearable
                disabled
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="条款" class="formRow">
              <!-- <el-input
            v-model="contractForm.lessorArticle"
            clearable
            type="textarea"
            rows="6"
            placeholder="请输入合同条款"
          ></el-input> -->
              <el-select
                v-model="contractForm.articleList.id"
                placeholder="请选择合同条款"
                style="width: 100%"
                clearable
                @change="getClauseById"
              >
                <el-option
                  v-for="item in articleList"
                  :key="item.id"
                  :label="item.articleTitle"
                  :value="item.id"
                />
              </el-select>
              <el-button type="primary" @click="showClauseDetail(articleItem)"
                >编辑</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签订时间" prop="orderTime">
              <el-date-picker
                v-model="contractForm.orderTime"
                type="date"
                placeholder="请选择签订时间"
                size="default"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="签订地点">
              <el-input
                v-model="contractForm.orderAddress"
                clearable
                placeholder="请输入签订地点"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货时间">
              <el-date-picker
                v-model="contractForm.deliveryTime"
                type="date"
                placeholder="请选择交货时间"
                size="default"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否是建模合同">
              <el-radio-group v-model="contractForm.modeling">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否含税">
              <el-radio-group v-model="contractForm.isIncludingTax">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="contractForm.isIncludingTax === 1">
            <el-form-item label="税率">
              <el-select
                v-model="contractForm.taxRate"
                placeholder="请选择税率"
                style="width: 100%"
                clearable
              >
                <el-option label="6%" value="1" />
                <el-option label="13%" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" style="width: 100%">
              <el-input
                v-model="contractForm.remark"
                clearable
                type="textarea"
                rows="6"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件">
              <sc-upload-file
                v-model="contractForm.otherFiles"
                :limit="10"
                :multiple="false"
                tip="最多上传10个文件,单个文件不要超过20M"
              >
                <el-button type="primary" plain icon="el-icon-upload"
                  >上传附件</el-button
                >
              </sc-upload-file>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-divider />
      <el-card
        shadow="hover"
        header="财务信息"
        class="item-background"
        style="width: 100%"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="收款人" prop="payee">
              <el-select
                v-model="contractForm.payee"
                placeholder="请选择收款人"
                style="width: 100%"
                clearable
                filterable
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!-- <el-form-item label="结算方式">
              <el-select
                v-model="contractForm.settlement"
                placeholder="请选择"
                clearable
                :disabled="settlementDisabled"
                style="width: 100%"
              >
                <el-option
                  v-for="item in settlementOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-select
                v-model="contractForm.paymentMethod"
                placeholder="选择付款方式"
                style="width: 100%"
                clearable
                disabled
                @change="changeCombination"
              >
                <el-option label="预付款" :value="1" />
                <el-option label="到付" :value="2" />
                <el-option label="约定时间" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="预付款"
              prop="prepaymentMoney"
              v-if="contractForm.paymentMethod === 1"
            >
              <el-input
                v-model="contractForm.prepaymentMoney"
                placeholder="请输入预付款"
                clearable
                @change="changePaymentMoney"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="组合方式"
              prop="combination"
              v-if="contractForm.paymentMethod === 1"
            >
              <el-select
                v-model="contractForm.combination"
                placeholder="选择付款组合方式"
                style="width: 100%"
                clearable
              >
                <el-option label="到付" :value="2" />
                <el-option label="约定时间" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="
                contractForm.paymentMethod === 3 ||
                contractForm.combination === 3
              "
              label="约定时间"
              prop="agreeTime"
            >
              <el-date-picker
                v-model="contractForm.agreeTime"
                type="date"
                placeholder="约定时间"
                size="default"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              /> </el-form-item
          ></el-col>
          <el-col :span="12"> </el-col>
        </el-row>
      </el-card>
      <el-divider />
      <el-card
        shadow="hover"
        header="生产信息"
        class="item-background"
        style="width: 100%"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产负责人" prop="productionPerson">
              <el-select
                v-model="contractForm.productionPerson"
                placeholder="请选择负责人"
                style="width: 100%"
                clearable
                filterable
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产截止时间" prop="endTime">
              <el-date-picker
                v-model="contractForm.endTime"
                type="date"
                placeholder="请选择生产截止时间"
                size="default"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-divider />
      <el-card
        shadow="hover"
        header="送货信息"
        class="item-background"
        style="width: 100%"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="送货人" prop="deliveryOfficer">
              <el-select
                v-model="contractForm.deliveryOfficer"
                placeholder="请选择送货人"
                style="width: 100%"
                clearable
                filterable
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货地址" prop="address">
              <el-input
                v-model="contractForm.address"
                placeholder="请输入收货地址"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <el-divider />
    <el-card
      shadow="hover"
      header="审核信息"
      class="item-background"
      style="width: 100%"
    >
      <check-form-item
        ref="checkFormItem"
        @setCheckConfig="setCheckConfig"
        :field="this.contractForm"
        :checkType="checkType"
        v-if="$route.query.mode == 'add'"
        style="width: 50%"
      ></check-form-item>
      <div class="button">
        <el-button type="primary" @click="save" :loading="isSaveing"
          >保 存</el-button
        >
        <el-button @click="cencel">取 消</el-button>
      </div>
    </el-card>
    <!-- 审核流程项 -->
  </div>
  <!-- </div> -->
  <clause-dialog ref="clauseDialog" @saveClauseDetail="saveClauseDetail">
  </clause-dialog>
</template>
<script>
import { queryTypeByDic } from "@/utils/getData"
import checkFormItem from "@/components/checkProcess/checkFormItem.vue"
import clauseDialog from "../components/clauseDialog.vue"
import { ElCard } from "element-plus"
export default {
  name: "",
  data () {
    return {
      checkType: 2, //工作流的类型
      isSaveing: false,
      selectQuotesLoading: false,
      //表单数据
      contractForm: {
        adminId: "", //跟进人id --登录时id
        departmentId: "",
        //customerId: '',
        num: "", //合同编号
        name: "", //合同名称
        simpleName: "", //合同简称
        lessor: "", //甲方
        lessorPhone: "", //甲方电话
        // secondPhone: '',//客户电话
        partyBName: "", //乙方名称
        type: 1, //合同类型
        money: "", //金额
        orderTime: this.$TOOL.dateFormat(new Date(), "yyyy-MM-dd"), //签订时间
        orderAddress: "", //签订地点
        deliveryTime: "", //交货时间
        // lessorArticle: '',//条款
        articleList: {}, //条款-*
        remark: "", //备注
        otherFiles: [], //附件
        workflowJsonList: [],
        // settlement: '',//结算方式
        quotesData: {}, //选择器数据
        paymentMethod: 3, //回款类型
        prepaymentMoney: "", //预付金额
        combination: "", //组合方式
        agreeTime: "", //约定时间
        productionPerson: "", //生产负责人
        payee: "", //收款人
        deliveryOfficer: "", //送货负责人
        endTime: "", // 生产截止时间
        address: "", // 送货地址
        exempt: "", //是否免审
        modeling: 0,//是否是建模合同
        isIncludingTax: 0, //	是否含税:0不含税，1含税
        taxRate: "", //税率
      },
      settlementOptions: [
        { name: "现结", value: 1 },
        { name: "月结", value: 2 },
      ],
      apiObj: this.$API.contract.quoteManagement.getStatusQuotes,
      quotesProps: {
        label: "quotesName",
        value: "id",
        keyword: "keyword",
      },
      articleList: [], //合同条款列表
      articleItem: [], //条款项
      contractType: [], //合同类型
      customerList: [], //客户列表
      userList: [], //用户列表
      settlementDisabled: false,
      //验证规则
      rules: {
        name: [{ required: true, message: "请输入合同名称" }],
        simpleName: [{ required: true, message: "请输入合同简称" }],
        lessor: [{ required: true, message: "请输入甲方" }],
        lessorPhone: [{ required: true, message: "请输入甲方电话" }],
        customerId: [{ required: true, message: "请选择客户", trigger: "change" }],
        partyBName: [{ required: true, message: "请输入乙方名称" }],
        type: [{ required: true, message: "请选择合同类型", trigger: "change" }],
        money: [{ required: true, message: "请输入合同金额" }],
        orderTime: [
          { type: "date", required: true, message: "请选择签订时间", trigger: "change" },
        ],
        quotesData: [{ required: true, message: "请选择报价", trigger: "change" }],
        paymentMethod: [{ required: true, message: "请选择付款方式", trigger: "change" }],
        prepaymentMoney: [{ required: true, message: "请输入预付款金额" }],
        isIncludingTax: [
          { required: true, message: "请勾选是否含税", trigger: "change" },
        ],
        combination: [
          { required: true, message: "请选择组合付款方式", trigger: "change" },
        ],
        agreeTime: [
          { type: "date", required: true, message: "请选择约定时间", trigger: "change" },
        ],
        productionPerson: [
          { required: true, message: "请选择生产负责人", trigger: "change" },
        ],
        payee: [{ required: true, message: "请选择组合付款方式", trigger: "change" }],
        deliveryOfficer: [
          { required: true, message: "请选择组合付款方式", trigger: "change" },
        ],
      },
    }
  },
  components: {
    checkFormItem,
    clauseDialog,
    ElCard,
  },
  mounted () {
    this.getContractConfig()
    this.getDefaultClause()
    this.getType()
    this.getArticleList()
    this.getUserList()

    if (this.$route.query.mode == "edit") {
      this.getContractById()
    }
    if (this.$route.query.quoteId) {
      this.getQuoteDetailById()
    }
  },
  methods: {
    changeCombination () {
      this.contractForm.combination = ""
    },

    // 根据报价id 获取报价详情
    async getQuoteDetailById () {
      let { data } = await this.$API.contract.quoteManagement.getQuoteDetailById.post({
        id: this.$route.query.quoteId,
      })
      this.contractForm.quotesData = data
      this.contractForm.name = "【" + data.customerName + "】的合同"
      this.contractForm.money = data.price
      this.contractForm.lessor = data.customerName
      let date = new Date()
      let time = data.deliveryTime ? +data.deliveryTime : 0
      date.setDate(date.getDate() + time)
      this.contractForm.deliveryTime = this.$TOOL.dateFormat(date, "yyyy-MM-dd")
      // this.contractForm.settlement = data.settlement
      // this.contractForm.settlement == 1 ? this.settlementDisabled = true : this.settlementDisabled = false

    },
    changePaymentMoney () {
      if (this.contractForm.prepaymentMoney > this.contractForm.money) {
        this.$message({
          message: '预付款金额不能大于合同总额',
          type: 'error'
        })
        this.contractForm.prepaymentMoney = this.contractForm.money
      }
    },
    // 跳转到报价详情
    toQuoteDetail () {
      if (!this.contractForm.quotesData.id) {
        this.$message.error("请选择报价")
        return
      }
      this.$router.push({
        path: "/customer/quoteManagement/quoteDetail",
        query: {
          id: this.contractForm.quotesData.id,
        },
      })
    },

    // 获取合同默认配置
    async getContractConfig () {
      let { data } = await this.$API.contract.contractConfig.getConfigDetail.post({
        id: 1,
      })
      this.contractForm.partyBName = data.partyBName
      this.contractForm.payee = data.payeeAdminId
      this.contractForm.productionPerson = data.produceAdminId
      this.contractForm.deliveryOfficer = data.deliverAdminId
      this.contractForm.orderAddress = data.signedAddress
    },

    // 获取合同类型
    async getType () {
      this.contractType = await queryTypeByDic("contractType")
    },
    // 选择器值变化时
    quotesChange (row) {
      this.contractForm.name = "【" + row.customerName + "】的合同"
      this.contractForm.money = row.price
      this.contractForm.lessor = row.customerName
      let date = new Date()
      let time = row.deliveryTime ? +row.deliveryTime : 0
      date.setDate(date.getDate() + time)
      this.contractForm.deliveryTime = this.$TOOL.dateFormat(date, "yyyy-MM-dd")
      // this.contractForm.settlement = row.settlement
      // this.contractForm.settlement == 1 ? this.settlementDisabled = true : this.settlementDisabled = false
    },
    // 获取合同条款列表
    async getArticleList () {
      let { data } = await this.$API.contract.contractClause.getClauseList.get()
      this.articleList = data
    },

    // 获取所有用户列表
    async getUserList (val) {
      let data = {
        limit: 1000,
        page: 1,
        search: val,
      }
      let res = await this.$API.user.getUserList.get(data)
      this.userList = res.data
    },

    // 搜索用户
    queryUser (val) {
      this.getUserList(val)
    },

    // 审批流配置
    setCheckConfig (list, exempt) {
      this.contractForm.workflowJsonList = list
      this.contractForm.exempt = exempt
    },

    // 根据id 获取合同详情
    async getContractById () {
      let { data } = await this.$API.contract.getContractById.post({
        id: this.$route.query.id,
      })
      this.contractForm = data
      this.contractForm.otherFiles.forEach((item) => {
        item.name = item.fileName
      })
      if (this.contractForm.articleList) {
        this.contractForm.articleList.articleText = this.contractForm.lessorArticle
        this.contractForm.articleList.articleTitle = this.contractForm.lessorArticleTitle
        this.articleItem = this.contractForm.articleList
      } else {
        this.contractForm.articleList = {}
      }

      console.log('this.contractForm')
      console.log(this.contractForm)
    },

    // 获取默认条款
    async getDefaultClause () {
      let { data } = await this.$API.contract.contractClause.getDefaultClause.get()
      this.contractForm.articleList = data
      this.articleItem = data
    },


    // 根据id获取条款详情
    async getClauseById (id) {
      let { data } = await this.$API.contract.contractClause.getClauseById.post({
        articleId: this.contractForm.articleList.id,
      })
      this.articleItem = data
    },

    // 查看条款详情
    showClauseDetail (data) {
      console.log(this.contractForm)
      // let detail = {}
      // if (this.$route.query.mode == 'edit') {
      //   // detail = {
      //   //   articleText: this.contractForm.lessorArticle,
      //   //   articleTitle: this.contractForm.lessorArticleTitle,
      //   //   id: this.articleItem.id
      //   // }
      //   detail = this.contractForm.articleList
      // } else {
      //   detail = data
      // }
      this.$refs.clauseDialog.open(data)
    },

    saveClauseDetail (data) {
      // console.log(data)
      this.contractForm.articleList = { ...data }

      this.articleItem = data
    },

    // 保存合同添加
    async save () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true
          let userInfo = this.$TOOL.data.get("USER_INFO")
          this.contractForm.adminId = userInfo.userId
          this.contractForm.departmentId = userInfo.departmentId
          this.$route.query.quoteId
            ? (this.contractForm.quotesId = this.$route.query.quoteId)
            : (this.contractForm.quotesId = this.contractForm.quotesData.id)

          let fileType = ""
          this.contractForm.otherFiles.map((item) => {
            if (item.url) {
              let arr = item.url.split(".")
              let type = arr[arr.length - 1]
              // fileType  1图片 2文件
              let imageType = "jpg/png/jpeg/svg"
              if (imageType.includes(type)) {
                fileType = 1
              } else {
                fileType = 2
              }
              item.fileType = fileType
              item.fileName = item.name
            }
          })
          let mode = this.$route.query.mode
          let res = null
          if (mode == "add") {
            let list = this.$refs.checkFormItem.initArr
            this.contractForm.workflowJsonList = list
            res = await this.$API.contract.addContract.post(this.contractForm)
          } else if (mode == "edit") {
            delete this.contractForm.workflowJsonList
            delete this.contractForm.lessorArticle
            delete this.contractForm.lessorArticleTitle
            res = await this.$API.contract.updateContract.post(this.contractForm)
          }
          if (res.code == 200) {
            this.$message.success("操作成功")
            this.isSaveing = false
            this.closeSelectedTag(this.$route)
            this.$router.push({
              path: "/contract/contractManagement",
            })
          }
        }
      })
    },
    // 取消合同添加
    cencel () {
      this.closeSelectedTag(this.$route)
      this.$router.push({
        path: "/contract/contractManagement",
      })
    },
    //关闭tag
    closeSelectedTag (tag) {
      this.$store.commit("removeViewTags", tag)
      this.$store.commit("removeIframeList", tag)
      this.$store.commit("removeKeepLive", tag.name)
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  margin: 10px;
}

.formBox {
  padding: 30px;
  background: #fff;

  .el-form {
    width: 100%;
  }
}
.formRow {
  :deep(.el-form-item__content) {
    flex-wrap: nowrap;
    .el-button {
      margin-left: 10px;
    }
  }
}
.button {
  margin-top: 50px;
  padding-left: 60px;
}

:deep(.el-divider__text) {
  padding: 0 10px;
  font-size: 18px;
  // font-weight: 600;
  background-color: #f6f8f9;
}

:deep(.el-form .el-form-item) {
  width: 80%;
}

.title {
  margin-top: 5px;
  color: #409eff;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
}
</style>
